<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Model
{
    const USER=0;
    const DEPT=1;
    /**
     * 用户数据
     * @var array
     * @var array.id
     * @var array.token
     */
    public $data;

    /**
     * 用户组
     * @var array
     */
    public $groups;
    //用户所属组织
    public $dept;

    function __construct()
    {
        $this->data = getToken();
    }


    /**
     * 检测用户是否登录
     * @return bool
     */
    function isLogin()
    {
        if ($this->data['id'] == 0) return false;
        $user = $this->db->select('id')
            ->where(['id' => $this->data['id'], 'token' => $this->data['token']])
            ->get('user')->row_array();
        if ($user) {
            define('UID', $this->data['id']);
            $this->_setGroups();
            return true;
        } else return false;
    }


    /**
     * 设置用户组信息
     */
    function _setGroups()
    {
        $data = $this->db->where(['uid' => $this->data['id']])
            ->get('userRole')->result_array();
        $this->groups = array_column($data,'rid');
        $data = $this->db->where(['uid' => $this->data['id']])
            ->get('userDept')->result_array();
        $this->dept = array_column($data,'did');
    }

   /**
    * 检查此用户是否有权限操作
    *
    * @param mixed $rid
    * @param int $type
    * @param bool $all 判断是否对所有组织有权限
    * @return bool
    */
    function checkRights($rid,int $type,bool $all=false):bool
    {
        if (in_array(1,$this->groups)) return true;//超级管理员直接过
        switch ($type) {
            case self::USER:
                $res=$this->db->where('uid',$rid)->where_in('did',$this->dept)->count_all_results('userDept');
                return $res>0;
                break;
            case self::DEPT:
                if (count($rid)==0) return false;
                $res=array_intersect($rid,$this->dept);
                return $all?count($res)==count($rid):count($res)>0;
                break;
            default:
                return false;
                break;
        }
    }

    function isAdmin():bool
    {
        return in_array(1,$this->groups);
    }
}
